package com.lwl;

import com.lwl.common.JSONSerializer;
import com.lwl.common.RpcDecoder;
import com.lwl.common.RpcRequest;
import com.lwl.handler.UserServiceHandler;
import com.lwl.handler.ZookeeperHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServerBoot {

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(ServerBoot.class, args);

        int port= 8090;

        //启动服务器
        startServer("127.0.0.1", port);

        String path = "/127.0.0.1:"+port;
        ZookeeperHandler.createNode(path);
        System.out.println("rpc-服务端以启动");
    }

    //启动服务器
    public static void startServer(String hostIp, int port) throws InterruptedException {
        //1.创建两个线程池对象
        //bossGroup 用于接收客户端传过来的请求
        //workerGroup 用于处理请求
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));


                        //把自定义的ChannelHander添加到责任链中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(hostIp, port).sync();
    }


}